package com.kamenrider.adventureaffiliated.procedures;

import com.kamenrider.adventureaffiliated.init.RiderAdventureAffiliatedModGeckoLibArmors;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;

public class AnotherBuildHenshinProcedure {

    private static final String ACTIVE_TAG = "adventure_affiliated:henshen_active";
    private static final String ORIGINAL_GEAR_TAG = "adventure_affiliated:original_gear";

    // 获取变身装备的Items
    private static final Item helmetItem = RiderAdventureAffiliatedModGeckoLibArmors.GeckoLibArmorItems.ANOTHER_BUILD_ARMOR_HELMET.get();
    private static final Item chestItem = RiderAdventureAffiliatedModGeckoLibArmors.GeckoLibArmorItems.ANOTHER_BUILD_ARMOR_CHESTPLATE.get();
    private static final Item legsItem = RiderAdventureAffiliatedModGeckoLibArmors.GeckoLibArmorItems.ANOTHER_BUILD_ARMOR_LEGGINGS.get();
    private static final Item bootsItem = RiderAdventureAffiliatedModGeckoLibArmors.GeckoLibArmorItems.ANOTHER_BUILD_ARMOR_BOOTS.get();

    public static void execute(LivingEntity entity) {
        if (entity == null) return;

        CompoundTag persistentData = entity.getPersistentData();
        boolean isActive = persistentData.contains(ACTIVE_TAG) && persistentData.getBoolean(ACTIVE_TAG);

        // 检测玩家当前是否穿着变身装备
        boolean isWearingTransformArmor = isWearingArmorPiece(entity, EquipmentSlot.HEAD, helmetItem) &&
                isWearingArmorPiece(entity, EquipmentSlot.CHEST, chestItem) &&
                isWearingArmorPiece(entity, EquipmentSlot.LEGS, legsItem) &&
                isWearingArmorPiece(entity, EquipmentSlot.FEET, bootsItem);

        // 如果是变身状态或者已经穿着变身装备，执行解除变身
        if (isActive || isWearingTransformArmor) {
            // 确保只有在有原始装备存储时才恢复
            if (persistentData.contains(ORIGINAL_GEAR_TAG, Tag.TAG_LIST)) {
                restoreOriginalGear(entity);
                }
            if (entity instanceof Player player) {
                player.displayClientMessage(
                        new TextComponent("§a变身解除!").withStyle(ChatFormatting.YELLOW),
                        true
                );
            }

            // 清理状态标记
            persistentData.remove(ACTIVE_TAG);
            persistentData.remove(ORIGINAL_GEAR_TAG);
        } else {
            // 仅在非变身状态保存装备
            saveOriginalGear(entity);

            // 变身逻辑
            equipFullArmorSet(entity);
            persistentData.putBoolean(ACTIVE_TAG, true);

            if (entity instanceof Player player) {
                player.displayClientMessage(
                        new TextComponent("§aBuild!").withStyle(ChatFormatting.YELLOW),
                        true
                );
            }
        }
    }

    // 检查是否穿着特定装备
    private static boolean isWearingArmorPiece(LivingEntity entity, EquipmentSlot slot, Item expectedItem) {
        ItemStack stack = entity.getItemBySlot(slot);
        return !stack.isEmpty() && stack.getItem() == expectedItem;
    }

    // 保存玩家原始装备（改进版本）
    private static void saveOriginalGear(LivingEntity entity) {
        // 如果已经存储过原始装备，不再重复存储
        if (entity.getPersistentData().contains(ORIGINAL_GEAR_TAG)) {
            return;
        }

        CompoundTag gearData = new CompoundTag();

        // 保存当前装备到不同标签
        saveItemSlot(gearData, "head", entity.getItemBySlot(EquipmentSlot.HEAD));
        saveItemSlot(gearData, "chest", entity.getItemBySlot(EquipmentSlot.CHEST));
        saveItemSlot(gearData, "legs", entity.getItemBySlot(EquipmentSlot.LEGS));
        saveItemSlot(gearData, "feet", entity.getItemBySlot(EquipmentSlot.FEET));

        // 直接使用复合标签而不是列表
        entity.getPersistentData().put(ORIGINAL_GEAR_TAG, gearData);
    }

    private static void saveItemSlot(CompoundTag gearData, String slot, ItemStack stack) {
        CompoundTag slotTag = new CompoundTag();
        if (!stack.isEmpty()) {
            stack.save(slotTag);
        }
        gearData.put(slot, slotTag);
    }

    // 恢复玩家原始装备（改进版本）
    private static void restoreOriginalGear(LivingEntity entity) {
        CompoundTag persistentData = entity.getPersistentData();
        if (persistentData.contains(ORIGINAL_GEAR_TAG, Tag.TAG_COMPOUND)) {
            CompoundTag gearData = persistentData.getCompound(ORIGINAL_GEAR_TAG);

            // 恢复每个装备槽
            entity.setItemSlot(EquipmentSlot.HEAD, loadItemSlot(gearData, "head"));
            entity.setItemSlot(EquipmentSlot.CHEST, loadItemSlot(gearData, "chest"));
            entity.setItemSlot(EquipmentSlot.LEGS, loadItemSlot(gearData, "legs"));
            entity.setItemSlot(EquipmentSlot.FEET, loadItemSlot(gearData, "feet"));
        }
    }

    private static ItemStack loadItemSlot(CompoundTag gearData, String slot) {
        if (gearData.contains(slot, Tag.TAG_COMPOUND)) {
            CompoundTag slotTag = gearData.getCompound(slot);
            if (!slotTag.isEmpty()) {
                return ItemStack.of(slotTag);
            }
        }
        return ItemStack.EMPTY;
    }

    // 装备全套变身盔甲
    private static void equipFullArmorSet(LivingEntity entity) {
        entity.setItemSlot(EquipmentSlot.HEAD, new ItemStack(helmetItem));
        entity.setItemSlot(EquipmentSlot.CHEST, new ItemStack(chestItem));
        entity.setItemSlot(EquipmentSlot.LEGS, new ItemStack(legsItem));
        entity.setItemSlot(EquipmentSlot.FEET, new ItemStack(bootsItem));
    }
}